const cloud = require('wx-server-sdk');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});

exports.main = async (event) => {
  const db = cloud.database();
  const _ = db.command;

  const wxContext = cloud.getWXContext()
  const id = event.id;

  console.log(id);

  if (id == null) {
    return {};
  }

  const result = await db
                .collection('records')
                .aggregate()
                .match({
                  _id: id
                }).lookup({
                  from: 'books',
                  localField: 'book',
                  foreignField: '_id',
                  as: 'book'
                }).limit(1)
                .end();

  return {
    event,
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID,
    result: result
  }
}
